import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:ecy_app_flutter/ecycommon/EcyAPI.dart';
import 'package:ecy_app_flutter/routes/blind_box/category_image_selector.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/EcyExchangeMarketPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxEnter extends StatefulWidget {
  const BlindBoxEnter({
    required super.key, 
    required this.commodityName, 
    required this.ipCode,
    required this.initialCommodityId,
    required this.ipName,
  });
    final String commodityName;
    final String ipCode;
    final String? initialCommodityId;
    final String ipName;

  @override
  State<BlindBoxEnter> createState() => _BlindBoxEnterState();
}

class _BlindBoxEnterState extends State<BlindBoxEnter> {
  _BlindBoxEnterState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;
  int _carouselIndex = 0;  // 轮播图当前索引
  int _selectedCommodityIndex = 0;  // 选中的商品索引
  bool _isDataLoaded = false;  // 添加数据加载标志

  final List<int> indexList = List.filled(19, 0);
  final List<BlindBoxPageMore> _commodityMoreList = [];

  @override
  void initState() {
    super.initState();
    _refreshData("");
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "current": _currentPage,
        "size": 10,
        "search": search,
        "ipCode": widget.ipCode,
        "illustratedHandbook": '1'
      };
      var response = await EcyRequestbasemanager().post(EcyAPI.blindBoxList.url, body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxPageMore> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxPageMore.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityMoreList = commonPage.records ?? [];
          if (_currentPage == 1) {
            _commodityMoreList.clear();
          }
          _commodityMoreList.addAll(commodityMoreList);
          
          // 在数据加载完成后，单独处理索引设置
          if (widget.initialCommodityId != null && _currentPage == 1) {
            int index = _commodityMoreList.indexWhere(
              (item) => item.commodityId == widget.initialCommodityId
            );
            if (index != -1) {
              _selectedCommodityIndex = index;
              _carouselIndex = index;
            }
          }
          
          if (mounted) {
            setState(() {
              _isDataLoaded = true;  // 设置数据加载完成标志
            });
          }
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0XFFF5F5F5),
        appBar: AppBar(
          title:  Text('${widget.ipName}', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w700, color: Color(0xFF000000)),),
          centerTitle: true,
          backgroundColor: const Color(0XFFF5F5F5),
          leadingWidth: 50.w,
          scrolledUnderElevation: 0,
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
          actions: [
            GestureDetector(
                onTap: () {},
                child: Padding(
                  padding: EdgeInsets.only(right: 12.w),
                  child: Image.asset(
                    'assets/images/kf.png',
                    width: 24.w,
                    height: 24.h,
                  ),
                )),
            GestureDetector(
                onTap: () {},
                child: Padding(
                    padding: EdgeInsets.only(right: 16.w),
                    child: Image.asset(
                      'assets/images/share.png',
                      width: 24.w,
                      height: 24.h,
                    )))
          ],
        ),
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(
                "assets/images/blind_box_bg@2x.png",
              ),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              _buildBoxHead(),
              Padding(padding: EdgeInsets.only(top: 32.h)),
              _buildBoxBody(),
              Padding(padding: EdgeInsets.only(top: 16.h)),
              GestureDetector(
              onTap: () {
                EcyRouter.push(context, EcyRouter.blindBoxChoose, { "commodityPageList": [_commodityMoreList[_carouselIndex]]});
              },
              child: SizedBox(
                width: 160.w,
                height: 60.h,
                child: DecoratedBox(
                    decoration: const BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                          "assets/images/box/join_box.png",
                        ),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: Center(
                      child: ShaderMask(
                        shaderCallback: (Rect bounds) {
                          return const LinearGradient(
                            colors: [Color(0xFFFCFCFC), Color(0xFFFFFFFF)],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            stops: [0.26, 0.76],
                          ).createShader(bounds);
                        },
                        blendMode: BlendMode.srcIn,
                        child: Text(
                          "进入选盒",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFFFFFFFF),
                          ),
                        ),
                      ),
                    )),
              ),
            ),
            
          ],
          
        ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: () {
            showModalBottomSheet(
              context: context,
              isScrollControlled: true, // 允许全屏
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              builder: (context) => Container(
                height: MediaQuery.of(context).size.height * 0.8,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                ),
                child: Center(child: EcyExchangeMarketPage()),
              ),
            );
          },
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
            ),
            height: 82.h,
            child: Column(
              
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Icon(CupertinoIcons.chevron_compact_up),
                SizedBox(height: 10.h),
                const Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text('互换集市'),
                    // Text('我的交换'),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 70.w, height: 70.h, fit: BoxFit.cover);

  Widget _buildBoxHead() {
    if (!_isDataLoaded || _commodityMoreList.isEmpty) {
      return Container(
        height: 130.h,
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFFFF),
          borderRadius: BorderRadius.all(Radius.circular(8.r)),
        ),
        child: Center(child: CircularProgressIndicator()),
      );
    }
    return CategoryImageSelector(
      key: ValueKey(_carouselIndex),
      commodityList: _commodityMoreList[_carouselIndex].commoditySkuVoList ?? []
    );
  }

  SizedBox _buildBoxBody() {
    if (!_isDataLoaded) {
      return SizedBox(
        height: 350.h,
        child: Center(child: CircularProgressIndicator()),
      );
    }

    return SizedBox(
      height: 350.h,
      child: Stack(
        children: [
          CarouselSlider.builder(
            itemCount: _commodityMoreList.length,
            options: CarouselOptions(
              aspectRatio: 5 / 4,
              enlargeCenterPage: true,
              viewportFraction: 0.75,
              initialPage: _carouselIndex,
              onPageChanged: (index, reason) {
                setState(() {
                  _carouselIndex = index;
                  _selectedCommodityIndex = index;  // 同步选中商品索引
                });
              },
            ),
            itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) {
              var item = _commodityMoreList[itemIndex];
              return Container(
                margin: const EdgeInsets.all(10.0),
                child: ClipRRect(
                  borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                  child: Stack(
                    children: <Widget>[
                      Image.network(
                        item.mainImageUrl ?? "",
                        fit: BoxFit.cover,
                        width: double.infinity,
                        height: 350.h,
                      ),
                      Positioned(
                        bottom: 0.0,
                        left: 0.0,
                        right: 0.0,
                        child: Container(
                          decoration: const BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                Color.fromARGB(200, 0, 0, 0),
                                Color.fromARGB(0, 0, 0, 0),
                              ],
                              begin: Alignment.bottomCenter,
                              end: Alignment.topCenter,
                            ),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                          child: Text(
                            item.commodityName ?? '未知商品',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 20.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }),
          // 右上角规则和详情按钮
          Positioned(
            top: 0,
            right: 15,
            child: Column(
              children: [
                _buildRuleOrDetailBtn('规则', Icons.assignment, () {
                  _showRuleOrDetailDialog(context, '规则', 'https://picsum.photos/200/100', '这里是规则的详细说明内容。');
                }),
                const SizedBox(height: 8),
                _buildRuleOrDetailBtn('详情', Icons.info_outline, () {
                  _showRuleOrDetailDialog(context, '详情', 'https://picsum.photos/200/100?2', '这里是详情的详细说明内容。');
                }),
                const SizedBox(width: 8),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRuleOrDetailBtn(String text, IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            Icon(icon, color: Color(0xFFF62EBD), size: 18),
            const SizedBox(width: 4),
            Text(
              text,
              style: const TextStyle(
                color: Color(0xFFF62EBD),
                fontWeight: FontWeight.w500,
                fontSize: 13,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showRuleOrDetailDialog(BuildContext context, String title, String imgUrl, String content) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                title,
                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black),
              ),
              const SizedBox(height: 16),
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(imgUrl, width: 200, height: 100, fit: BoxFit.cover),
              ),
              const SizedBox(height: 16),
              Text(
                content,
                style: const TextStyle(fontSize: 15, color: Colors.black87),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
